﻿using Grasshopper;
using Grasshopper.Kernel;
using Grasshopper.Kernel.Types;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Windows.Forms;

namespace D006_EventRemove
{
    public class Component_EventRemove : GH_PersistentParam<GH_Integer>
    {
        protected override System.Drawing.Bitmap Icon => null;
        public override Guid ComponentGuid => new Guid("E9C9E750-269F-4D7C-8B9D-E97A1DDE41FC");

        private GH_Integer value;

        BindingFlags binding = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;


        public Component_EventRemove()
          : base("Component_Event", "Nickname",
              "Description",
              "PluginTest", "Event")
        {
            value = new GH_Integer() { Value = 5 };

            var canvas = Instances.ActiveCanvas;

            this.SetPersistentData(value);

            if (canvas != null)
            {
                canvas.KeyDown += Canvas_KeyDown2;

                // 所有事件都按照事件名保存在这 事件类型---委托 键值对
                FieldInfo events = typeof(Component).GetField("events", binding);
                var eventHandlerList = events.GetValue((Control)canvas) as EventHandlerList;

                // KeyDown事件类型
                FieldInfo keyDownTypeInfo = typeof(Control).GetField("EventKeyDown", binding);
                object keyDownType = keyDownTypeInfo.GetValue(canvas);

                // KeyDown事件的委托
                Delegate keyDownDelegate = eventHandlerList[keyDownType];
                // 移除委托
                canvas.KeyDown -= (KeyEventHandler)keyDownDelegate;
                var b = eventHandlerList[keyDownType]; //null


                // KeyUp事件类型
                FieldInfo keyUpTypeInfo = typeof(Control).GetField("EventKeyUp", binding);
                object keyUpType = keyUpTypeInfo.GetValue(canvas);

                // KeyUp事件的委托
                Delegate keyUpDelegate = eventHandlerList[keyUpType];
                // 移除委托
                canvas.KeyUp -= (KeyEventHandler)keyUpDelegate;

            }
        }

        private void Canvas_KeyDown2(object sender, KeyEventArgs e)
        {
            value.Value += 1;
        }

        protected override GH_GetterResult Prompt_Singular(ref GH_Integer value)
        {
            return GH_GetterResult.cancel;
        }

        protected override GH_GetterResult Prompt_Plural(ref List<GH_Integer> values)
        {
            return GH_GetterResult.cancel;
        }
    }
}